<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Category extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->model('category_model');
        $this->load->library('upload');
        $this->load->model('novel_model');
    }

    public function index() {
        $cats = $this->category_model->getCategory_all();
        foreach ($cats as &$cat) {
            $cat->count = $this->category_model->countNovel_by_category($cat->id);
        }
        $this->load->view('category/list', array('cats' => $cats));
    }
    
    public function get($catId = 0) {
        if ($catId == 0) {
            show_404();
            die();
        }
        
        $data = $this->novel_model->getNovel_byCate($catId);
        $this->load->view('novel/all', array('novel' => $data));
    }
    
    function ajax_add_new_category() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        $arr = $this->category_model->addCategory_validate($_POST);
        if ($arr['err'] == 0) {
            extract($_POST);
            $name = !isset($name) ? '' : $name;
            $data = array('name' => trim($name));
            $arr['err'] = $this->category_model->addCategory($data) ? 0 : -1;
        }
        echo json_encode($arr);
    }
    
    function ajax_edit_category_name() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }
        
        if (!isset($_POST['id'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing parameter.'));
            die;
        }

        $arr = $this->category_model->addCategory_validate($_POST);
        if ($arr['err'] == 0) {
            extract($_POST);
            $data = array('id' => $id,  'name' => trim($name), 'slug' => slug(trim($name)));
            $arr['err'] = $this->category_model->editCategory($data) ? 0 : -1;
            $arr['data'] = $data;
        }
        echo json_encode($arr);
    }
    
    function ajax_delete_category() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['id'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing parameter.'));
            die;
        }

        $id = $_POST['id'];
        $rm = $this->category_model->removeCategory($id);
        if ($rm)
            echo json_encode(array('err' => 0, 'msg' => 'Successfull.'));
        else
            echo json_encode(array('err' => -1, 'msg' => 'Something wrong...'));
    }

}